package com.unionftech.content_login.ui.forget

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.unionftech.common.R.*
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.RegexUtils
import com.unionftech.content_login.R
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.content_login.bean.request.ForgetPasswordRequest
import com.unionftech.common.common.bean.request.SendCodeRequest
import com.unionftech.common.utils.CheckInputUtil

class EmailForgetPasswordFragment : BaseFragment() {
    private val mEtEmail: EditText by lazy { mRootView.findViewById(R.id.et_email) }
    private val mIvClearEmail: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_email) }
    private val mTvEmailError: TextView by lazy { mRootView.findViewById(R.id.tv_email_error) }
    private lateinit var mCommonFragment: ForgetPasswordCommonFragment
    private var mRequestListener: ((request: ForgetPasswordRequest) -> Unit)? = null
    private lateinit var mCountryInfo: CountryInfo

    companion object {
        @JvmStatic
        fun newInstance() = EmailForgetPasswordFragment().apply {
            arguments = Bundle().apply {

            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_email_forget_password, container, false)
    }

    override fun initData() {
        super.initData()
        mCommonFragment =
            ForgetPasswordCommonFragment.newInstance(ForgetPasswordCommonFragment.TYPE_REGISTER_EMAIL)
        mCommonFragment.setCompleteListener {
            mEtEmail.clearFocus()
            if (checkInput() && it) {
                requestResetPwd()
            }
        }
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mEtEmail.hint =
            DynamicResourceManager.getString(mContext, string.email)
    }

    override fun setListener() {
        super.setListener()
        mCommonFragment.setGetParentValueListener {
            if (checkInput()) {
                if (::mCountryInfo.isInitialized) {
                    return@setGetParentValueListener SendCodeRequest(
                        loginEmail = mEtEmail.text.toString(),
                        check = true,
                        isContact = false,
                        businessType = 2
                    )
                }
            }
            return@setGetParentValueListener null
        }
        mIvClearEmail.setOnClickListener(this)
        mEtEmail.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                mEtEmail.isSelected = false
                setClearEmail(mEtEmail.text)
            } else {
                mIvClearEmail.visibility = View.GONE
                checkInput()
            }
        }
        mEtEmail.addTextChangedListener { text ->
            setClearEmail(text)
            val enable = !TextUtils.isEmpty(text)
            val result = mCommonFragment.getInputEnable() && enable
            mCommonFragment.setConfirmEnable(result)
        }
        mCommonFragment.setInputChangeCallBack {
            val result = mCommonFragment.getInputEnable() && !TextUtils.isEmpty(mEtEmail.text)
            mCommonFragment.setConfirmEnable(result)
        }
    }

    private fun setClearEmail(text: Editable?) {
        if (!TextUtils.isEmpty(text)) {
            mIvClearEmail.visibility = View.VISIBLE
        } else {
            mIvClearEmail.visibility = View.GONE
        }
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        //editText的左右padding不一致，目前只能在代码中设置，在xml中设置不支持rtl
        val dp16 = mContext.resources.getDimension(dimen.dp_16).toInt()
        val dp48 = mContext.resources.getDimension(dimen.dp_48).toInt()
        mEtEmail.setPaddingRelative(dp16, 0, dp48, 0)
        mRootView.setBackgroundColor(mContext.getColor(android.R.color.transparent))
        val beginTransaction = childFragmentManager.beginTransaction()
        beginTransaction.add(R.id.fl_forget_common, mCommonFragment)
        beginTransaction.commitNowAllowingStateLoss()
        childFragmentManager.executePendingTransactions()
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_clear_email -> mEtEmail.setText("")
        }
    }

    fun setCountryInfo(countryInfo: CountryInfo) {
        mCountryInfo = countryInfo
    }

    fun setRequestListener(listener: (request: ForgetPasswordRequest) -> Unit) {
        this.mRequestListener = listener
    }

    private fun requestResetPwd() {
        val request =
            mCommonFragment.getResetRequestInfo().copy(loginEmail = mEtEmail.text.toString())
        mRequestListener?.invoke(request)
    }

    private fun checkInput(): Boolean {
        return CheckInputUtil.checkInput(
            mEtEmail.text.toString(),
            RegexUtils.EMAIL_REGEX,
            mEtEmail,
            mTvEmailError,
            string.email_empty,
            string.email_format_incorrect
        )
    }

    fun resetData() {
        mEtEmail.setText("")
        mCommonFragment.resetData()
    }

}